package com.niknik.woody.utils.wunit.junit.runner;

import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;

import java.util.List;

import static java.text.MessageFormat.format;

public final class WUnitRunner
    extends BlockJUnit4ClassRunner {

  private static boolean isRunnerUsed = false;

  public WUnitRunner(Class<?> clazz)
      throws InitializationError {
    super(clazz);
  }

  public static WUnitContext getContext() {
    if (!isRunnerUsed) {
      throw new AssertionError(format("WUnit functionality requires @{0}({1}.class) annotation on your test class",
          RunWith.class.getSimpleName(), WUnitRunner.class.getSimpleName()));
    }
    return WUnitContext.INSTANCE;
  }

  @Override
  protected void runChild(FrameworkMethod method, RunNotifier notifier) {
    isRunnerUsed = true;
    WUnitContext.INSTANCE.reset();
    super.runChild(method, notifier);
    isRunnerUsed = false;
  }

  @Override
  protected List<TestRule> getTestRules(Object target) {
    List<TestRule> rules = super.getTestRules(target);
    rules.addAll(WUnitContext.INSTANCE.getRules());
    return rules;
  }
}